import json
import csv
import random
from datetime import datetime
from datetime import timedelta
from faker import Faker
import os

fake = Faker('zh_CN')

# 业务类型到产品类别的映射
business_mapping = {
    '水产': ['即烹', '即热'],
    '养殖': ['即配', '即烹'],
    '蔬菜': ['即食', '即配'],
    '肉制品': ['即烹', '即热'],
    '预制菜': ['即热', '即食'],
    '调味料': ['即配'],
    '速冻': ['即烹'],
    '饲料': ['即配'],
    '禽类': ['即烹'],
    '火锅': ['即热']
}

# 产品类型模板库
product_templates = {
    '水产': ['香辣{水产}','清蒸{水产}','蒜蓉{水产}','麻辣{水产}','红烧{水产}'],
    '蔬菜': ['酸辣{蔬菜}','酱香{蔬菜}','香脆{蔬菜}','凉拌{蔬菜}','泡椒{蔬菜}'],
    '肉类': ['五香{肉类}','黑椒{肉类}','红烧{肉类}','香辣{肉类}','酱卤{肉类}'],
    '禽类': ['香酥{禽类}','卤味{禽类}','椒盐{禽类}','麻辣{禽类}','白切{禽类}'],
    '预制菜': ['{菜系}风味{主料}','即食{菜品}','方便{菜品}','速食{菜品}']
}


# 新增主料数据源
main_ingredients = {
    '水产': ['鱼片','虾仁','扇贝','鲍鱼','鱿鱼'],
    '肉类': ['牛肉','猪肉','羊肉','排骨'],
    '禽类': ['鸡胸肉','鸭脖','鹌鹑蛋'],
    '通用': ['豆腐','菌菇','时蔬']
}

# 生成产品编码
def generate_code(supplier_id, seq):
    random_date = datetime.now() - timedelta(days=random.randint(0, 29))
    date_str = random_date.strftime("%Y%m%d")
    return f"SP-{date_str}-{seq:03d}"

# 领域关键词库（可继续扩展）
keywords = {
    '水产': {
        '原料': ['深海捕捞', '活鲜急冻', '纯净水域养殖'],
        '工艺': ['低温锁鲜', '去鳞去内脏', '独立速冻'],
        '品质': ['肉质紧实', '口感鲜美', '营养丰富'],
        '场景': ['家庭聚餐', '火锅伴侣', '宝宝辅食']
    },
    '肉类': {
        '原料': ['谷饲喂养', '天然牧草', '排酸处理'],
        '工艺': ['低温慢煮', '秘制腌制', '精准切割'],
        '品质': ['肥瘦相间', '肉香浓郁', '汁水饱满'],
        '场景': ['烧烤食材', '中式爆炒', '西式煎烤']
    },
    '蔬菜': {
        '原料': ['有机种植', '当季采收', '无农药残留'],
        '工艺': ['人工精选', '超声波清洗', '急速锁鲜'],
        '品质': ['清脆爽口', '色泽鲜亮', '膳食纤维丰富'],
        '场景': ['沙拉轻食', '清炒时蔬', '炖汤配料']
    }
}

# 结构化描述模板
description_templates = [
    "本产品精选{原料}，采用{工艺}工艺制作，{品质}。适合{场景}，{场景}。",
    "{原料}结合{工艺}技术，打造{品质}的优质产品。推荐用于{场景}或{场景}。",
    "严选{原料}原料，通过{工艺}工艺处理，{品质}，是{场景}的理想选择。"
]

def generate_description(business_type):
    """生成结构化产品描述"""
    try:
        # 获取领域关键词
        k = keywords[business_type]
        
        # 从模板库随机选择模板
        template = random.choice(description_templates)
        
        # 填充模板内容
        return template.format(
            原料=random.choice(k['原料']),
            工艺=random.choice(k['工艺']),
            品质=random.choice(k['品质']),
            场景="、".join(random.sample(k['场景'], 2))
        )
    except KeyError:
        # 通用保底描述
        return f"优质食品，采用先进工艺制作，满足多种烹饪需求。{fake.sentence()}"
    
# 生成营养信息
def generate_nutrition():
    return {
        "热量": f"{random.randint(200,800)}kJ",
        "蛋白质": f"{random.uniform(5,30):.1f}g",
        "脂肪": f"{random.uniform(1,25):.1f}g",
        "碳水化合物": f"{random.uniform(10,50):.1f}g"
    }

# 生成产品数据
def generate_products(supplier):


    products = []
    business_type = next((k for k in business_mapping if k in supplier['business']), '其他')
    
    # 根据业务类型确定生成数量
    num_products = random.randint(3,10)
    
    for i in range(num_products):
        # 生成产品名称
        if '水产' in business_type:
            name = random.choice(product_templates['水产']).format(水产=random.choice(['鲍鱼','虾仁','鱼片','扇贝','鱿鱼']))
        elif '蔬菜' in business_type:
            name = random.choice(product_templates['蔬菜']).format(蔬菜=random.choice(['藕片','笋尖','木耳','蕨菜','包菜']))
        elif '肉' in business_type:
            name = random.choice(product_templates['肉类']).format(肉类=random.choice(['牛肉','猪肉','羊肉','肉丸','排骨']))
        elif '禽' in business_type:
            name = random.choice(product_templates['禽类']).format(禽类=random.choice(['鸡翅','鸭脖','鹌鹑','鸡胸肉','鸭掌']))
        else:
            ingredient_type = next((k for k in ['水产','肉类','禽类'] if k in supplier['business']), '通用')
            name = random.choice(product_templates['预制菜']).format(
                菜系=random.choice(['川味','湘式','广式','江浙']),
                主料=random.choice(main_ingredients[ingredient_type]),
                菜品=random.choice(['酸菜鱼','佛跳墙','梅菜扣肉','红烧肉'])
            )

        # 生成产品数据
        product = {
            'name': name,
            'supplier_id': int(supplier['id']),
            'code': generate_code(int(supplier['id']), i+1),
            'category': random.choice(business_mapping.get(business_type, ['即热'])),
            'description': generate_description(business_type),
            'shelf_life': random.choice([30,60,90,180,365]),
            'storage_conditions': random.choice(['冷冻保存(-18℃以下)','冷藏保存(0~4℃)','常温保存']),
            'net_weight': f"{random.randint(200,1000)}g/{random.choice(['盒','袋','罐'])}",
            'nutrition_info': json.dumps(generate_nutrition(), ensure_ascii=False),
            'image_url': f"/product_images/{datetime.now().strftime('%Y%m%d')}/{supplier['id']}_{i+1}.jpg",
            'status': 'active'
        }
        products.append(product)
    return products

# 主程序
def main():
    try:
        # 读取供应商数据
        with open('suppliers.json', 'r', encoding='utf-8') as f:
            suppliers = json.load(f)
            if not suppliers:
                print("供应商数据为空，请检查 suppliers.json 文件。")
                return
        
        # 生成产品数据
        all_products = []
        for supplier in suppliers:
            all_products.extend(generate_products(supplier))
        
        if not all_products:
            print("没有生成任何产品数据。")
            return
        
        # 写入CSV
        with open('products.csv', 'w', newline='', encoding='utf-8') as csvfile:
            fieldnames = ['name','supplier_id','code','category','description',
                         'shelf_life','storage_conditions','net_weight',
                         'nutrition_info','image_url','status']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(all_products)
        
        output_path = os.path.abspath('products.csv')
        print(f"产品数据已生成至：{output_path}")

    except Exception as e:
        print(f"程序发生错误: {e}")

if __name__ == '__main__':
    main()